<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>二手易购 - 我的商品</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    /* 全局样式 */
    :root {
      --primary: #1a1a1a;
      --secondary: #333333;
      --accent: #666666;
      --light: #f5f5f5;
      --white: #ffffff;
      --dark: #000000;
      --light-gray: #e0e0e0;
      --medium-gray: #999999;
      --success: #28a745;
      --error: #dc3545;
      --warning: #ffc107;
      --shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
      --transition: all 0.2s ease;
    }

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
    }

    body {
      background: linear-gradient(135deg, #f8f9fa 0%, #eef0f2 100%);
      color: var(--dark);
      min-height: 100vh;
      padding-bottom: 80px;
    }

    /* 顶部导航栏 */
    .navbar {
      background: var(--white);
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
      padding: 12px 30px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      position: sticky;
      top: 0;
      z-index: 1000;
    }

    .logo {
      display: flex;
      align-items: center;
      transform-origin: left center;
    }

    .logo:hover {
      transform: scale(1.03);
    }

    .logo h1 {
      font-size: 22px;
      font-weight: 700;
      color: var(--dark);
      margin-left: 8px;
      letter-spacing: -0.5px;
    }

    .logo i {
      font-size: 24px;
      color: var(--accent);
    }

    .search-container {
      flex: 1;
      max-width: 550px;
      margin: 0 15px;
      position: relative;
    }

    .search-container input {
      width: 100%;
      padding: 12px 20px;
      border: 1px solid var(--light-gray);
      border-radius: 25px;
      font-size: 14px;
      transition: var(--transition);
      background-color: var(--white);
      color: var(--dark);
      outline: none;
      padding-right: 45px;
      box-shadow: 0 3px 8px rgba(0, 0, 0, 0.05);
    }

    .search-container input:focus {
      box-shadow: 0 3px 12px rgba(0, 0, 0, 0.1);
      border-color: var(--accent);
    }

    .search-container button {
      position: absolute;
      right: 8px;
      top: 50%;
      transform: translateY(-50%);
      background: none;
      border: none;
      color: var(--accent);
      cursor: pointer;
      font-size: 16px;
    }

    .nav-links {
      display: flex;
      gap: 20px;
    }

    .nav-link {
      display: flex;
      flex-direction: column;
      align-items: center;
      text-decoration: none;
      color: var(--dark);
      font-size: 13px;
      transition: var(--transition);
      position: relative;
      padding: 4px 8px;
      border-radius: 6px;
    }

    .nav-link i {
      font-size: 18px;
      margin-bottom: 3px;
    }

    .nav-link:hover {
      color: var(--accent);
      background-color: rgba(0, 0, 0, 0.03);
    }

    .nav-link .badge {
      position: absolute;
      top: -4px;
      right: -4px;
      background-color: var(--error);
      color: var(--white);
      border-radius: 50%;
      width: 18px;
      height: 18px;
      font-size: 11px;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 2px 4px rgba(0,0,0,0.15);
    }

    .user-menu {
      display: flex;
      align-items: center;
      cursor: pointer;
      position: relative;
    }

    .user-avatar {
      width: 38px;
      height: 38px;
      border-radius: 50%;
      background: linear-gradient(135deg, #e0e0e0, #f0f0f0);
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      margin-left: 12px;
      box-shadow: 0 2px 6px rgba(0,0,0,0.1);
    }

    .user-avatar img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .user-avatar i {
      font-size: 18px;
      color: var(--accent);
    }

    .dropdown-menu {
      position: absolute;
      top: 50px;
      right: 0;
      background: var(--white);
      box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
      border-radius: 10px;
      width: 180px;
      overflow: hidden;
      display: none;
      z-index: 1000;
      animation: fadeIn 0.3s ease;
    }

    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(-10px); }
      to { opacity: 1; transform: translateY(0); }
    }

    .dropdown-menu.show {
      display: block;
    }

    .dropdown-item {
      padding: 10px 16px;
      display: flex;
      align-items: center;
      text-decoration: none;
      color: var(--dark);
      transition: var(--transition);
      position: relative;
      font-size: 14px;
    }

    .dropdown-item:hover {
      background-color: rgba(0, 0, 0, 0.05);
      padding-left: 20px;
    }

    .dropdown-item:hover::before {
      content: "";
      position: absolute;
      left: 0;
      top: 0;
      height: 100%;
      width: 3px;
      background: var(--dark);
    }

    .dropdown-item i {
      margin-right: 8px;
      width: 18px;
      text-align: center;
      font-size: 14px;
    }

    .divider {
      height: 1px;
      background-color: var(--light-gray);
      margin: 4px 0;
    }

    /* 内容区域 */
    .container {
      max-width: 1300px;
      margin: 25px auto;
      padding: 0 20px;
    }

    /* 页面标题 */
    .page-title {
      text-align: center;
      margin: 35px 0 45px;
      position: relative;
    }

    .page-title h2 {
      font-size: 32px;
      font-weight: 800;
      letter-spacing: -1px;
      margin-bottom: 12px;
      color: var(--dark);
    }

    .page-title p {
      font-size: 17px;
      color: var(--medium-gray);
      max-width: 550px;
      margin: 0 auto;
      line-height: 1.6;
    }

    .page-title::after {
      content: '';
      position: absolute;
      bottom: -18px;
      left: 50%;
      transform: translateX(-50%);
      width: 90px;
      height: 3px;
      background: var(--dark);
      border-radius: 2px;
    }

    /* 商品网格 */
    .products-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 25px;
      margin-bottom: 35px;
    }

    .product-card {
      background: var(--white);
      border-radius: 14px;
      overflow: hidden;
      box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
      transition: var(--transition);
      cursor: pointer;
      position: relative;
      transform: translateY(0);
      opacity: 1;
      border: 1px solid rgba(0, 0, 0, 0.05);
    }

    .product-card:hover {
      transform: translateY(-6px);
      box-shadow: 0 12px 30px rgba(0, 0, 0, 0.15);
    }

    .product-image {
      width: 100%;
      height: 200px;
      background: linear-gradient(135deg, #f0f0f0, #e0e0e0);
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      position: relative;
    }

    .product-image::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 35%;
      background: linear-gradient(to top, rgba(0,0,0,0.1), transparent);
    }

    .product-image img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.4s ease;
    }

    .product-card:hover .product-image img {
      transform: scale(1.08);
    }

    .product-info {
      padding: 20px;
      position: relative;
    }

    .product-name {
      font-size: 18px;
      font-weight: 700;
      margin-bottom: 10px;
      color: var(--dark);
    }

    .product-card:hover .product-name {
      color: var(--accent);
    }

    .product-meta {
      display: flex;
      flex-wrap: wrap;
      gap: 12px;
      margin-bottom: 15px;
    }

    .meta-item {
      display: flex;
      align-items: center;
      font-size: 14px;
      color: var(--medium-gray);
    }

    .meta-item i {
      margin-right: 6px;
      font-size: 14px;
    }

    .price-stock {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 15px;
      padding-top: 15px;
      border-top: 1px solid var(--light-gray);
    }

    .product-price {
      font-size: 20px;
      font-weight: 800;
      color: var(--dark);
      letter-spacing: -0.5px;
    }

    .stock-info {
      font-size: 14px;
      font-weight: 500;
      color: var(--dark);
      padding: 5px 12px;
      border-radius: 20px;
      background-color: rgba(0, 0, 0, 0.05);
    }

    .stock-info.in-stock {
      background-color: rgba(40, 167, 69, 0.1);
      color: var(--success);
    }

    .stock-info.out-of-stock {
      background-color: rgba(220, 53, 69, 0.1);
      color: var(--error);
    }

    .product-actions {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 10px;
      margin-top: 20px;
    }

    .action-btn {
      padding: 10px;
      border-radius: 8px;
      font-weight: 600;
      cursor: pointer;
      transition: var(--transition);
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
      border: 2px solid var(--dark);
      background: transparent;
      color: var(--dark);
      font-size: 14px;
    }

    .action-btn.edit:hover {
      background: var(--dark);
      color: var(--white);
    }

    .action-btn.delete {
      border-color: var(--error);
      color: var(--error);
    }

    .action-btn.delete:hover {
      background: var(--error);
      color: var(--white);
    }

    .action-btn.activate {
      border-color: var(--success);
      color: var(--success);
    }

    .action-btn.activate:hover {
      background: var(--success);
      color: var(--white);
    }

    .action-btn.deactivate {
      border-color: var(--warning);
      color: var(--warning);
    }

    .action-btn.deactivate:hover {
      background: var(--warning);
      color: var(--white);
    }

    .product-status {
      position: absolute;
      top: 15px;
      right: 15px;
      padding: 5px 15px;
      border-radius: 20px;
      font-size: 12px;
      font-weight: 600;
      z-index: 2;
      box-shadow: 0 2px 6px rgba(0,0,0,0.15);
    }

    .status-active {
      background-color: rgba(40, 167, 69, 0.15);
      color: var(--success);
    }

    .status-inactive {
      background-color: rgba(220, 53, 69, 0.15);
      color: var(--error);
    }

    .status-trading {
      background-color: rgba(255, 193, 7, 0.15);
      color: var(--warning);
    }

    /* 空状态 */
    .empty-state {
      text-align: center;
      padding: 70px 20px;
      color: var(--medium-gray);
      background: var(--white);
      border-radius: 14px;
      box-shadow: var(--shadow);
      margin-top: 30px;
    }

    .empty-state i {
      font-size: 60px;
      margin-bottom: 20px;
      opacity: 0.2;
    }

    .empty-state h3 {
      font-size: 24px;
      margin-bottom: 15px;
      color: var(--secondary);
      font-weight: 700;
    }

    .empty-state p {
      font-size: 16px;
      max-width: 450px;
      margin: 0 auto 30px;
      line-height: 1.6;
    }

    .add-goods-btn {
      display: inline-flex;
      align-items: center;
      padding: 12px 25px;
      border-radius: 10px;
      font-size: 16px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s ease;
      background: var(--dark);
      color: var(--white);
      border: none;
      position: relative;
      overflow: hidden;
      letter-spacing: 0.5px;
      gap: 8px;
      text-decoration: none;
    }

    .add-goods-btn:hover {
      background: #111;
      transform: translateY(-3px);
      box-shadow: 0 10px 22px rgba(0,0,0,0.25);
    }

    /* 编辑商品模态框 */
    .edit-modal {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.7);
      z-index: 2000;
      display: none;
      justify-content: center;
      align-items: center;
    }

    .edit-content {
      background: var(--white);
      border-radius: 16px;
      width: 500px;
      max-width: 90%;
      padding: 30px;
      box-shadow: 0 20px 45px rgba(0,0,0,0.2);
      position: relative;
    }

    .edit-close {
      position: absolute;
      top: 15px;
      right: 15px;
      font-size: 24px;
      cursor: pointer;
      color: var(--medium-gray);
      transition: var(--transition);
    }

    .edit-close:hover {
      color: var(--dark);
    }

    .edit-title {
      font-size: 24px;
      font-weight: 700;
      margin-bottom: 25px;
      text-align: center;
      color: var(--dark);
    }

    .form-group {
      margin-bottom: 20px;
    }

    .form-label {
      display: block;
      margin-bottom: 8px;
      font-weight: 600;
      color: var(--dark);
    }

    .form-control {
      width: 100%;
      padding: 12px 15px;
      border: 1px solid var(--light-gray);
      border-radius: 8px;
      font-size: 16px;
      transition: var(--transition);
      background-color: var(--white);
      color: var(--dark);
      outline: none;
    }

    .form-control:focus {
      border-color: var(--accent);
      box-shadow: 0 0 0 3px rgba(102, 102, 102, 0.1);
    }

    .form-textarea {
      min-height: 120px;
      resize: vertical;
    }

    .edit-actions {
      display: flex;
      gap: 15px;
      justify-content: center;
      margin-top: 25px;
    }

    .edit-btn {
      padding: 12px 25px;
      border-radius: 10px;
      font-size: 16px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s ease;
      border: none;
      min-width: 120px;
    }

    .edit-btn.cancel {
      background: var(--light-gray);
      color: var(--dark);
    }

    .edit-btn.cancel:hover {
      background: #ddd;
    }

    .edit-btn.save {
      background: var(--dark);
      color: var(--white);
    }

    .edit-btn.save:hover {
      background: #111;
    }

    /* 响应式设计 */
    @media (max-width: 992px) {
      .navbar {
        flex-wrap: wrap;
        padding: 12px 15px;
      }

      .logo h1 {
        font-size: 18px;
      }

      .search-container {
        order: 3;
        max-width: 100%;
        margin: 12px 0 0;
      }

      .nav-links {
        gap: 12px;
      }
    }

    @media (max-width: 768px) {
      .nav-links {
        display: none;
      }

      .products-grid {
        grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
        gap: 18px;
      }

      .product-image {
        height: 180px;
      }

      .product-actions {
        grid-template-columns: 1fr;
      }
    }

    @media (max-width: 576px) {
      .products-grid {
        grid-template-columns: 1fr;
      }

      .price-stock {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
      }
    }

    /* 加载动画 */
    .loader {
      text-align: center;
      padding: 50px 0;
    }

    .loader .spinner {
      width: 50px;
      height: 50px;
      border: 4px solid rgba(0, 0, 0, 0.1);
      border-radius: 50%;
      border-top-color: var(--dark);
      animation: spin 1.2s linear infinite;
      margin: 0 auto 15px;
    }

    @keyframes spin {
      to { transform: rotate(360deg); }
    }

    /* 确认模态框 */
    .confirm-modal {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.7);
      z-index: 2000;
      display: none;
      justify-content: center;
      align-items: center;
    }

    .confirm-content {
      background: var(--white);
      border-radius: 16px;
      width: 400px;
      padding: 30px;
      box-shadow: 0 20px 45px rgba(0,0,0,0.2);
      text-align: center;
    }

    .confirm-icon {
      font-size: 48px;
      margin-bottom: 20px;
    }

    .confirm-icon.warning {
      color: var(--warning);
    }

    .confirm-icon.error {
      color: var(--error);
    }

    .confirm-title {
      font-size: 22px;
      font-weight: 700;
      margin-bottom: 15px;
    }

    .confirm-message {
      font-size: 16px;
      color: var(--medium-gray);
      margin-bottom: 25px;
      line-height: 1.6;
    }

    .confirm-actions {
      display: flex;
      gap: 15px;
      justify-content: center;
    }

    .confirm-btn {
      padding: 12px 25px;
      border-radius: 10px;
      font-size: 16px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s ease;
      border: none;
    }

    .confirm-btn.cancel {
      background: var(--light-gray);
      color: var(--dark);
    }

    .confirm-btn.cancel:hover {
      background: #ddd;
    }

    .confirm-btn.confirm {
      background: var(--error);
      color: var(--white);
    }

    .confirm-btn.confirm:hover {
      background: #c82333;
    }

    .confirm-btn.success {
      background: var(--success);
      color: var(--white);
    }

    .confirm-btn.success:hover {
      background: #218838;
    }

    /* 用户菜单激活状态 */
    .user-menu.active .dropdown-menu {
      display: block;
    }

    .user-menu.active .user-avatar {
      background: linear-gradient(135deg, #d0d0d0, #e0e0e0);
    }
  </style>
</head>
<body>
<!-- 顶部导航栏 -->
<nav class="navbar">
  <div class="logo">
    <i class="fas fa-recycle"></i>
    <h1>二手易购</h1>
  </div>

  <div class="nav-links">
    <a href="productPage.html" class="nav-link">
      <i class="fas fa-home"></i>
      <span>首页</span>
    </a>
    <a href="#" class="nav-link active">
      <i class="fas fa-box"></i>
      <span>我的商品</span>
    </a>
    <a href="orders.html" class="nav-link">
      <i class="fas fa-file-invoice"></i>
      <span>订单</span>
    </a>
    <a href="my-comments.html" class="nav-link">
      <i class="fas fa-comment-alt"></i>
      <span>评论</span>
    </a>
    <a href="cart.html" class="nav-link">
      <i class="fas fa-shopping-cart"></i>
      <span>购物车</span>
    </a>
  </div>

  <div class="user-menu" id="userMenu">
    <span id="usernameDisplay">用户</span>
    <div class="user-avatar">
      <i class="fas fa-user"></i>
    </div>
    <div class="dropdown-menu" id="dropdownMenu">
      <a href="profile.html" class="dropdown-item">
        <i class="fas fa-user-circle"></i>个人中心
      </a>
      <div class="divider"></div>
      <a href="#" class="dropdown-item" id="logoutLink">
        <i class="fas fa-sign-out-alt"></i>退出登录
      </a>
    </div>
  </div>
</nav>

<!-- 主内容区域 -->
<div class="container">
  <div class="page-title">
    <h2>我的商品</h2>
    <p>管理您发布的二手商品，编辑信息或下架不再出售的物品</p>
  </div>

  <!-- 商品网格 -->
  <div class="products-grid" id="productsGrid">
    <!-- 商品卡片将通过JS动态加载 -->
  </div>

  <!-- 加载动画 -->
  <div class="loader" id="loader">
    <div class="spinner"></div>
    <p>正在加载商品...</p>
  </div>

  <!-- 空状态 -->
  <div class="empty-state" id="emptyState" style="display: none;">
    <i class="fas fa-box-open"></i>
    <h3>您还没有发布商品</h3>
    <p>开始发布您的第一件二手商品，让闲置物品找到新主人</p>
    <a href="publish.html" class="add-goods-btn">
      <i class="fas fa-plus"></i> 发布商品
    </a>
  </div>
</div>

<!-- 编辑商品模态框 -->
<div class="edit-modal" id="editModal">
  <div class="edit-content">
    <div class="edit-close" id="editClose">
      <i class="fas fa-times"></i>
    </div>
    <h3 class="edit-title">编辑商品信息</h3>

    <form id="editForm">
      <input type="hidden" id="editGoodsId">

      <div class="form-group">
        <label class="form-label">商品名称</label>
        <input type="text" id="editName" class="form-control" placeholder="输入商品名称" required>
      </div>

      <div class="form-group">
        <label class="form-label">价格 (¥)</label>
        <input type="number" id="editPrice" class="form-control" placeholder="输入价格" min="0" step="0.01" required>
      </div>

      <div class="form-group">
        <label class="form-label">库存数量</label>
        <input type="number" id="editStock" class="form-control" placeholder="输入库存数量" min="0" required>
      </div>

      <div class="form-group">
        <label class="form-label">商品类别</label>
        <input type="text" id="editCategory" class="form-control" placeholder="输入商品类别" required>
      </div>

      <div class="form-group">
        <label class="form-label">商品描述</label>
        <textarea id="editDescription" class="form-control form-textarea" placeholder="详细描述您的商品..." required></textarea>
      </div>

      <div class="edit-actions">
        <button type="button" class="edit-btn cancel" id="editCancelBtn">取消</button>
        <button type="button" class="edit-btn save" id="editSaveBtn">保存修改</button>
      </div>
    </form>
  </div>
</div>

<!-- 确认模态框 -->
<div class="confirm-modal" id="confirmModal">
  <div class="confirm-content">
    <div class="confirm-icon warning" id="confirmIcon">
      <i class="fas fa-exclamation-triangle"></i>
    </div>
    <h3 class="confirm-title" id="confirmTitle">确认操作</h3>
    <p class="confirm-message" id="confirmMessage">您确定要执行此操作吗？</p>
    <div class="confirm-actions">
      <button class="confirm-btn cancel" id="cancelBtn">取消</button>
      <button class="confirm-btn confirm" id="confirmBtn">确认</button>
    </div>
  </div>
</div>
<script>
  // 用户信息（从localStorage中获取）
  let userInfo = JSON.parse(localStorage.getItem('userInfo')) || null;
  let currentGoodsId = null;
  let currentAction = null;
  const API_BASE_URL = 'http://localhost:8080';

  // DOM元素
  const productsGrid = document.getElementById('productsGrid');
  const loader = document.getElementById('loader');
  const emptyState = document.getElementById('emptyState');
  const confirmModal = document.getElementById('confirmModal');
  const confirmIcon = document.getElementById('confirmIcon');
  const confirmTitle = document.getElementById('confirmTitle');
  const confirmMessage = document.getElementById('confirmMessage');
  const cancelBtn = document.getElementById('cancelBtn');
  const confirmBtn = document.getElementById('confirmBtn');
  const userMenu = document.getElementById('userMenu');
  const dropdownMenu = document.getElementById('dropdownMenu');
  const logoutLink = document.getElementById('logoutLink');

  // 编辑模态框元素
  const editModal = document.getElementById('editModal');
  const editClose = document.getElementById('editClose');
  const editCancelBtn = document.getElementById('editCancelBtn');
  const editSaveBtn = document.getElementById('editSaveBtn');
  const editGoodsId = document.getElementById('editGoodsId');
  const editName = document.getElementById('editName');
  const editPrice = document.getElementById('editPrice');
  const editStock = document.getElementById('editStock');
  const editCategory = document.getElementById('editCategory');
  const editDescription = document.getElementById('editDescription');

  // 初始化页面
  document.addEventListener('DOMContentLoaded', function() {
    // 更新用户信息显示
    updateUserInfo();

    // 加载用户商品
    loadUserGoods();

    // 设置事件监听器
    setupEventListeners();
  });

  // 更新用户信息显示
  function updateUserInfo() {
    if (userInfo) {
      document.getElementById('usernameDisplay').textContent = userInfo.username || '用户';
    } else {
      // 如果用户未登录，跳转到登录页
      window.location.href = 'login.html';
    }
  }

  // 设置事件监听器
  function setupEventListeners() {
    // 用户菜单点击事件
    userMenu.addEventListener('click', function(e) {
      e.stopPropagation();
      userMenu.classList.toggle('active');
    });

    // 点击页面其他地方关闭菜单
    document.addEventListener('click', function(e) {
      if (!userMenu.contains(e.target)) {
        userMenu.classList.remove('active');
      }
    });

    // 退出登录
    logoutLink.addEventListener('click', function(e) {
      e.preventDefault();
      localStorage.removeItem('userInfo');
      window.location.href = 'login.html';
    });

    // 确认模态框按钮
    cancelBtn.addEventListener('click', function() {
      confirmModal.style.display = 'none';
    });

    confirmBtn.addEventListener('click', function() {
      confirmModal.style.display = 'none';
      performAction();
    });

    // 编辑模态框关闭事件
    editClose.addEventListener('click', closeEditModal);
    editCancelBtn.addEventListener('click', closeEditModal);

    // 编辑模态框保存事件
    editSaveBtn.addEventListener('click', saveGoodsChanges);

    // 点击模态框外部关闭
    editModal.addEventListener('click', function(e) {
      if (e.target === editModal) {
        closeEditModal();
      }
    });
  }

  // 关闭编辑模态框
  function closeEditModal() {
    editModal.style.display = 'none';
  }

  // 加载用户商品
  function loadUserGoods() {
    loader.style.display = 'block';
    productsGrid.innerHTML = '';

    if (!userInfo || !userInfo.userId) {
      loader.style.display = 'none';
      return;
    }

    fetch(`${API_BASE_URL}/Goods/user/${userInfo.userId}`)
            .then(response => {
              if (!response.ok) {
                throw new Error('获取商品失败');
              }
              return response.json();
            })
            .then(goodsList => {
              loader.style.display = 'none';

              if (goodsList.length > 0) {
                renderGoodsList(goodsList);
                productsGrid.style.display = 'grid';
                emptyState.style.display = 'none';
              } else {
                productsGrid.style.display = 'none';
                emptyState.style.display = 'block';
              }
            })
            .catch(error => {
              console.error('获取用户商品失败:', error);
              loader.style.display = 'none';
              productsGrid.style.display = 'none';
              emptyState.style.display = 'block';
            });
  }

  // 渲染商品列表
  function renderGoodsList(goodsList) {
    goodsList.forEach(goods => {
      const card = document.createElement('div');
      card.className = 'product-card';
      card.dataset.id = goods.gId;

      // 格式化日期
      const createDate = goods.gCreateTime ? new Date(goods.gCreateTime).toLocaleDateString() : '未知日期';

      // 状态标签
      let statusClass = 'status-inactive';
      let statusText = '已下架';

      if (goods.gIsActive) {
        statusClass = 'status-active';
        statusText = '上架中';
      }

      card.innerHTML = `
        <div class="product-image">
          <img src="${goods.gImage || 'https://via.placeholder.com/300x300?text=No+Image'}" alt="${goods.gName}">
          <div class="product-status ${statusClass}">${statusText}</div>
        </div>
        <div class="product-info">
          <h3 class="product-name">${goods.gName}</h3>
          <div class="product-meta">
            <div class="meta-item">
              <i class="fas fa-tag"></i> ${goods.gCategory || '未分类'}
            </div>
            <div class="meta-item">
              <i class="fas fa-calendar"></i> ${createDate}
            </div>
          </div>
          <div class="price-stock">
            <div class="product-price">¥${goods.gPrice?.toFixed(2) || '0.00'}</div>
            <div class="stock-info ${goods.gStockQuantity > 0 ? 'in-stock' : 'out-of-stock'}">
              库存: ${goods.gStockQuantity}件
            </div>
          </div>
          <div class="product-actions">
            <button class="action-btn edit">
              <i class="fas fa-edit"></i> 编辑
            </button>
            <button class="action-btn delete">
              <i class="fas fa-trash"></i> 删除
            </button>
            ${goods.gIsActive ?
              `<button class="action-btn deactivate">
                <i class="fas fa-eye-slash"></i> 下架
              </button>` :
              `<button class="action-btn activate">
                <i class="fas fa-eye"></i> 上架
              </button>`}
          </div>
        </div>
      `;

      productsGrid.appendChild(card);

      // 添加按钮事件
      card.querySelector('.action-btn.edit').addEventListener('click', function(e) {
        e.stopPropagation();
        editGoods(goods.gId);
      });

      card.querySelector('.action-btn.delete').addEventListener('click', function(e) {
        e.stopPropagation();
        showConfirm('删除商品', '您确定要永久删除此商品吗？此操作不可撤销。', 'error', goods.gId, 'delete');
      });

      if (goods.gIsActive) {
        card.querySelector('.action-btn.deactivate').addEventListener('click', function(e) {
          e.stopPropagation();
          showConfirm('下架商品', '您确定要下架此商品吗？下架后用户将无法查看和购买此商品。', 'warning', goods.gId, 'deactivate');
        });
      } else {
        card.querySelector('.action-btn.activate').addEventListener('click', function(e) {
          e.stopPropagation();
          showConfirm('上架商品', '您确定要上架此商品吗？上架后用户将可以查看和购买此商品。', 'success', goods.gId, 'activate');
        });
      }
    });
  }

  // 显示编辑商品模态框
  function editGoods(goodsId) {
    // 获取商品详细信息
    fetch(`${API_BASE_URL}/Goods/detail/${goodsId}`)
            .then(response => {
              if (!response.ok) {
                throw new Error('获取商品详情失败');
              }
              return response.json();
            })
            .then(goods => {
              // 填充表单数据
              editGoodsId.value = goods.gId;
              editName.value = goods.gName;
              editPrice.value = goods.gPrice;
              editStock.value = goods.gStockQuantity;
              editCategory.value = goods.gCategory;
              editDescription.value = goods.gDescription;

              // 显示模态框
              editModal.style.display = 'flex';
            })
            .catch(error => {
              console.error('获取商品详情失败:', error);
              alert('获取商品详情失败，请稍后重试');
            });
  }

  // 保存商品修改
  function saveGoodsChanges() {
    // 获取表单数据
    const goodsId = editGoodsId.value;
    const name = editName.value;
    const price = parseFloat(editPrice.value);
    const stock = parseInt(editStock.value);
    const category = editCategory.value;
    const description = editDescription.value;

    // 验证数据
    if (!name || !price || isNaN(price) || !stock || isNaN(stock) || !category || !description) {
      alert('请填写所有必填字段');
      return;
    }

    // 构造更新对象
    const updatedGoods = {
      gId: parseInt(goodsId),
      gName: name,
      gPrice: price,
      gStockQuantity: stock,
      gCategory: category,
      gDescription: description
    };

    // 发送PUT请求更新商品
    fetch(`${API_BASE_URL}/Goods/update`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(updatedGoods)
    })
            .then(response => {
              if (!response.ok) {
                throw new Error('更新商品失败');
              }
              return response.json();
            })
            .then(data => {
              alert('商品信息更新成功！');
              closeEditModal();
              // 重新加载商品列表
              loadUserGoods();
            })
            .catch(error => {
              console.error('更新商品失败:', error);
              alert('更新商品失败: ' + error.message);
            });
  }

  // 显示确认模态框
  function showConfirm(title, message, iconType, goodsId, action) {
    confirmTitle.textContent = title;
    confirmMessage.textContent = message;

    // 设置图标
    confirmIcon.innerHTML = '';
    let iconClass = 'fas ';
    if (iconType === 'error') {
      iconClass += 'fa-exclamation-circle';
    } else if (iconType === 'warning') {
      iconClass += 'fa-exclamation-triangle';
    } else if (iconType === 'success') {
      iconClass += 'fa-check-circle';
    }

    const icon = document.createElement('i');
    icon.className = iconClass;
    confirmIcon.appendChild(icon);

    // 设置确认按钮样式
    confirmBtn.className = 'confirm-btn confirm';
    if (iconType === 'success') {
      confirmBtn.classList.add('success');
    } else if (iconType === 'error') {
      confirmBtn.classList.add('confirm');
    }

    currentGoodsId = goodsId;
    currentAction = action;
    confirmModal.style.display = 'flex';
  }

  // 执行操作
  function performAction() {
    if (!currentGoodsId || !currentAction) return;

    let url, method, successMessage;

    switch(currentAction) {
      case 'delete':
        url = `${API_BASE_URL}/Goods/delete/${currentGoodsId}`;
        method = 'DELETE';
        successMessage = '商品删除成功';
        break;
      case 'activate':
        url = `${API_BASE_URL}/Goods/status/${currentGoodsId}?active=true`;
        method = 'PUT';
        successMessage = '商品已上架';
        break;
      case 'deactivate':
        url = `${API_BASE_URL}/Goods/status/${currentGoodsId}?active=false`;
        method = 'PUT';
        successMessage = '商品已下架';
        break;
      default:
        return;
    }

    fetch(url, {
      method: method,
      headers: {
        'Content-Type': 'application/json'
      }
    })
            .then(response => {
              if (!response.ok) {
                throw new Error('操作失败');
              }
              return response.text();
            })
            .then(message => {
              alert(successMessage);
              // 刷新商品列表
              loadUserGoods();
            })
            .catch(error => {
              console.error(`${currentAction}操作失败:`, error);
              alert(`操作失败: ${error.message}`);
            });
  }

</script>
</body>
</html>